package crossbreed.views.Controls;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Shape;
import java.util.LinkedList;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
import javax.swing.text.LayeredHighlighter;
import javax.swing.text.View;

public class LineHighlighter extends LayeredHighlighter
{
	private JTextComponent component;
	private LayeredHighlighter internalInstance;
	private LinkedList<LineHighlight> highlights;
	
	public LineHighlighter(LayeredHighlighter internalInstance)
	{
		this.internalInstance = internalInstance;
		highlights = new LinkedList<LineHighlight>();
	}
	
	@Override
	public Object addHighlight(int p0, int p1, HighlightPainter p) throws BadLocationException
	{
		return internalInstance.addHighlight(p0, p1, p);
	}
	
	public void addLineHighlighter(int lineStart, Color c)
	{
		LineHighlight newHighlight = new LineHighlight();
		newHighlight.color = c;
		newHighlight.startPosition = lineStart;
		highlights.add(newHighlight);
	}

	@Override
	public void changeHighlight(Object tag, int p0, int p1) throws BadLocationException
	{
		internalInstance.changeHighlight(tag, p0, p1);
	}

	@Override
	public void deinstall(JTextComponent c)
	{
		component = null;
		internalInstance.deinstall(c);
	}

	@Override
	public Highlight[] getHighlights()
	{
		return internalInstance.getHighlights();
	}

	@Override
	public void install(JTextComponent c)
	{
		component = c;
		internalInstance.install(c);
	}

	@Override
	public void paint(Graphics g)
	{
		try
		{
			for (LineHighlight highlight : highlights)
			{
				Rectangle rect = component.modelToView(highlight.startPosition);
				g.setColor(highlight.color);
				g.fillRect(rect.x, rect.y, component.getWidth(), rect.height);
			}
			
			internalInstance.paint(g);
		}
		catch (Exception e)
		{
			
		}
	}

	@Override
	public void removeAllHighlights()
	{
		internalInstance.removeAllHighlights();
	}

	@Override
	public void removeHighlight(Object tag)
	{
		internalInstance.removeHighlight(tag);
	}
	
	public void adjustHighlights(int offset, int length)
	{
		for (LineHighlight highlight : highlights)
		{
			if (offset <= highlight.startPosition)
			{
				highlight.startPosition += length;
			}
		}
	}
	
	@Override
	public void paintLayeredHighlights(Graphics g, int p0, int p1, Shape viewBounds,
			JTextComponent editor, View view)
	{
		internalInstance.paintLayeredHighlights(g, p0, p1, viewBounds, editor, view);
	}
	
	class LineHighlight
	{
		public Color color;
		public int startPosition;
	}
}
